export function buildIntersectionObserver(
  callback: (entries: IntersectionObserverEntry[]) => void
) {
  let observer: IntersectionObserver | null = null;
  if (process.client) {
    observer = new IntersectionObserver(callback, {
      // rootMargin: "-120px 1px 1px 1px",
      threshold: 0.4, // 元素的可视区域 >= 40% 视为与根元素相交，根元素默认是浏览器视口
    });
  }
  return observer;
}

/**
 * 添加监听
 * @param elDom 待监听的html元素
 * @param observer IntersectionObserver实例
 */
export function addObserve<ELE extends HTMLElement>(
  elDom: ELE | undefined,
  observer: IntersectionObserver | null
) {
  if (process.client && observer && elDom) {
    observer.observe(elDom);
  }
}

/**
 * 删除监听
 * @param elDom 待删除监听的html元素
 * @param observer IntersectionObserver实例
 */
export function removeObserve<ELE extends HTMLElement>(
  elDom: ELE | undefined,
  observer: IntersectionObserver | null,
  disconnect: boolean = false
) {
  if (process.client && observer) {
    if (elDom) {
      observer.unobserve(elDom);
    }
    disconnect && observer.disconnect();
  }
}

/**
 * 判断目标元素是否与根元素相交
 * @param entries 被观察的实体
 * @param targetDom 目标元素
 * @returns
 */
export function targetDomIsCrossRoot<ELE extends HTMLElement>(
  entries: IntersectionObserverEntry[],
  targetDom: ELE
) {
  let isCross = false;
  for (let i = 0; i < entries.length; i++) {
    const entry = entries[i];
    // entry.isIntersecting 值为true表示当前元素与根元素相交
    if (entry.isIntersecting && entry.target === targetDom) {
      isCross = true;
      break;
    }
  }
  return isCross;
}
